<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="40px">
<!--      <el-form-item label="类别" prop="category">-->
<!--        <el-input v-model="queryParams.category" placeholder="请输入类别" clearable @keyup.enter.native="handleQuery"/>-->
<!--      </el-form-item>-->
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ex:question_bank:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['ex:question_bank:remove']">删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="question_bankList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="名称" align="center" prop="name">
        <template slot-scope="scope">
          <router-link :to="'/ex/see_apply_info/index/' + scope.row.id" class="link-type">
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="报名起始和截止时间" align="center" prop="info">
        <template slot-scope="scope">
          {{JSON.parse(scope.row.info)[0]}}~{{JSON.parse(scope.row.info)[1]}}
        </template>
      </el-table-column>
      <el-table-column label="总题数" align="center" prop="total"/>
<!--      <el-table-column label="类别" align="center" prop="trainFlag">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.ex_question_bank_train" :value="scope.row.trainFlag"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="考试日期范围" align="center" prop="reservedOne">
        <template slot-scope="scope">
          <el-popover placement="top" width="400" trigger="hover">
            <el-table :data="scope.row.reservedTwoList">
              <el-table-column prop="name" label="名称" width="150px"></el-table-column>
              <el-table-column label="开始时间">
                <template slot-scope="scope1">
                  <el-tag>{{scope1.row.time[0]}}</el-tag>~
                  <el-tag type="success">{{scope1.row.time[1]}}</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-tag slot="reference" type="success" effect="plain">{{scope.row.reservedOneList[0]}}~{{scope.row.reservedOneList[1]}}</el-tag>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status==0 ? '启用' : '禁用'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ex:question_bank:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ex:question_bank:remove']">删除</el-button>
          <el-button size="mini" type="text" :icon="scope.row.status==0 ? 'el-icon-circle-close':'el-icon-circle-check'"
                     @click="updateStatus(scope.row)" v-hasPermi="['ex:question_bank:edit']">
            {{ scope.row.status==0 ? '禁用' : '启用'}}
          </el-button>
<!--          <el-button size="mini" type="text" icon="el-icon-message" @click="handleSms(scope.row)" v-hasPermi="['ex:question_bank:edit']">短信通知</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改题库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" destroy-on-close append-to-body :before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="left" status-icon>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择班级" class="input-w-250" clearable>
            <el-option v-for="item in training_classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>  <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" class="input-w-250" clearable/>
        </el-form-item>
<!--        <el-form-item label="类别" prop="trainFlag">-->
<!--          <el-radio-group v-model="form.trainFlag" size="small">-->
<!--            <el-radio-button v-for="dict in dict.type.ex_question_bank_train" :label="dict.value">{{dict.label}}</el-radio-button>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="考试时间范围" prop="reservedOne">
          <el-date-picker v-model="form.reservedOne" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="报名起始和截止时间" prop="info">
          <el-date-picker v-model="form.info" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="考试时间段" prop="reservedTwo">
          <el-button type="primary" size="mini" @click="addOneReservedTwo" round>添加一行</el-button>
          <div v-for="(item,index) in form.reservedTwo">
            <el-input @input="$forceUpdate()" v-model="item.name" placeholder="时段名称" size="mini" class="input-w-100 mr7" clearable/>
            <el-time-picker @input="$forceUpdate()" size="mini" is-range v-model="item.time" class="mr7"
                            range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"/>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="delOneReservedTwo(index)" circle/>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 短信通知弹窗 -->
    <el-dialog title="发送短信通知" :visible.sync="sms.open" width="900px" append-to-body>
      <el-row>
        <el-col :span="12">
          <div style="width: 50%;position: relative;float: left;">
            <img :src="phoneSms" style="width: 300px;height: 600px" alt="">
            <p style="width: 200px;position:absolute;top:34%;left:56%;transform: translate(-50%, -50%);font-weight: bold;font-size: 15px;">
              【公卫处方权中心】{{ sms.content }}</p>
          </div>
        </el-col>
        <el-col :span="10" style="float: left;margin-top: 200px">
          <el-form ref="form" :model="sms" label-width="120px">
            <el-form-item label="通知班级(可多选)" prop="classId">
              <el-select v-model="sms.classId" multiple placeholder="请选择班级">
                <el-option v-for="item in training_classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
<!--            <el-form-item label="类别" prop="trainFlag">-->
<!--              <el-radio-group v-model="sms.trainFlag" size="small">-->
<!--                <el-radio-button v-for="dict in dict.type.ex_question_bank_train" :label="dict.value">{{dict.label}}</el-radio-button>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" icon="el-icon-message" @click="sendSms" style="margin-top: 30px;width: 200px;height: 100px">发送</el-button>
            </el-form-item>
          </el-form>

        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {delQuestion_bank, addQuestion_bank, updateQuestion_bank, listQuestion_bank_ex,smsSend_people_count,smsSend} from "@/api/ex/question_bank";
import {listTraining_class} from "@/api/pv/training_class";
import {dealDateToUnix, parseTime} from "@/utils/ruoyi";
import {copyObj, strFormat,isNull} from "@/utils/zzDouUtils/ObjUtil";
import {isEmptyArr} from "@/utils/zzDouUtils/arrayUtil";
import phoneSms from "@/assets/images/phone_sms.png";

export default {
  name: "Question_bank",
  dicts: ['ex_question_bank_train'],
  data() {
    var infoValidator = (rule, value, callback) => {
      if (!this.form.isClazzEx && (value == null || value == '' || value == undefined)) {
        callback(new Error('请选择预约时间范围'));
      } else if (this.form.isClazzEx) {
        if (value===undefined || value === null || value.length <= 0){
          callback(new Error('请选择预约时间范围'));
        }else{
          if (value[1].getTime() > this.form.reservedOne[0].getTime()){//预约截止时间不可大于考试开始时间
             callback(new Error('预约截止时间不可大于考试开始时间'))
           }
        }
      }
      callback();
    };
    var reservedOneValidator = (rule, value, callback) => {
      if (this.form.isClazzEx) {
        if (value===undefined || value === null || value.length <= 0){
          callback(new Error('请选择考试时间范围'));
        }
      }
      callback();
    };
    return {
      training_classList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库表格数据
      question_bankList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        info: null,
        category: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classId: [
          { required: true, message: "请选择班级", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        // trainFlag: [
        //   { required: true, message: "请选择类别", trigger: "blur" }
        // ],
        info: [
          { validator: infoValidator, trigger: "blur" }
        ],
        reservedOne: [
          { validator: reservedOneValidator, trigger: "blur" }
        ]
      },
      lookTwo:{
        open:false,
        obj:{},
      },
      phoneSms: phoneSms,
      //短信通知
      sms:{
        open: false,
        bean: null,
        content: '',
        classId:[],
        trainFlag:null,
      },
    };
  },
  created() {
    this.getList();
    this.getTrainingList();
  },
  methods: {
    /** 查询培训班管理列表 */
    getTrainingList() {
      listTraining_class({pageSize: 1000,pageNum: 1}).then(response => {
        this.training_classList = response.rows;
      });
    },
    /** 查询题库列表 */
    getList() {
      this.loading = true;
      listQuestion_bank_ex(this.queryParams).then(response => {
        this.question_bankList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classId: null,
        name: null,
        trainFlag: null,
        info: null,
        category: null,
        status: null,
        deptId: null,
        reservedOne: null,
        reservedTwo: [{name:'',time:[new Date('1970-01-01 00:00:00'),new Date('1970-01-01 00:00:00')]}],
        isEx: '1',
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {...row};
      this.form.info = [];
      for (let i = 0; i < row.appointDateRange.length; i++) {
        this.form.info[i] = new Date(row.appointDateRange[i]);
      }
      this.form.reservedOne = [];
      for (let i = 0; i < row.reservedOneList.length; i++) {
        this.form.reservedOne[i] = new Date(row.reservedOneList[i]);
      }
      this.form.reservedTwo = [];
      for (let i = 0; i < row.reservedTwoList.length; i++) {
        var times = row.reservedTwoList[i];
        var obj = {name:times.name+'', time:[]};
        console.log(obj)
        var tt = times.time;
        for (let j = 0; j < tt.length; j++) {
          obj.time[j] = dealDateToUnix(tt[j])
        }
        this.form.reservedTwo[i] = obj;
      }
      this.open = true;
      this.title = "修改题库";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          var formFlag = {...this.form};
          for (let i = 0; i < formFlag.info.length; i++) {
            formFlag.info[i] = parseTime(formFlag.info[i],"{y}-{m}-{d}");
          }
          formFlag.info = JSON.stringify(formFlag.info);
          for (let i = 0; i < formFlag.reservedOne.length; i++) {
            formFlag.reservedOne[i] = parseTime(formFlag.reservedOne[i],"{y}-{m}-{d}");
          }
          formFlag.reservedOne = JSON.stringify(formFlag.reservedOne);
          for (let i = 0; i < formFlag.reservedTwo.length; i++) {
            var time = formFlag.reservedTwo[i].time;
            for (let j = 0; j < time.length; j++) {
              time[j] = parseTime(time[j],"{h}:{i}:{s}");
            }
            formFlag.reservedTwo[i].time = time;
          }
          formFlag.reservedTwo = JSON.stringify(formFlag.reservedTwo);
          if (formFlag.id != null) {
            updateQuestion_bank(formFlag).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion_bank(formFlag).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //修改状态按钮
    updateStatus(row){
      row.status = (row.status==1) ? 0 : 1;
      updateQuestion_bank(row).then(response => {
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题库编号为"' + ids + '"的数据项？').then(function () {
        return delQuestion_bank(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ex/question_bank/export', {
        ...this.queryParams
      }, `question_bank_${new Date().getTime()}.xlsx`)
    },
    addOneReservedTwo(){
      this.form.reservedTwo.push({name:'',time:[new Date('1970-01-01 00:00:00'),new Date('1970-01-01 00:00:00')]});
    },
    delOneReservedTwo(index){
      if (this.form.reservedTwo.length > 1){
        this.$delete(this.form.reservedTwo,index);
      }
    },
    /** 打开短信通知弹窗 */
    handleSms(row){
      this.sms.bean = copyObj(row);
      this.sms.content = strFormat('张三您好，${year}产褥期保健上岗培训班的操作考试将于${date}至${date1},每日${time}进行。请登录微信小程序“公卫处方权培训基地”，进行线上预约，并按期参加。',{
        year: parseTime(new Date(),'{y}'),
        date: parseTime(row.reservedOneList[0],'{y}-{m}-{d}'),
        date1: parseTime(row.reservedOneList[1],'{y}-{m}-{d}'),
        time: row.reservedTwoList[0].time[0],
      });
      this.sms.open = true;
    },
    /** 发送短信 */
    sendSms(){
      if (isEmptyArr(this.sms.classId)){
        this.$modal.msgWarning("请选择班级")
        return;
      }
      if (isNull(this.sms.trainFlag)){
        this.$modal.msgWarning("请选择类别")
        return;
      }

      smsSend_people_count(this.sms.classId,this.sms.trainFlag).then(response=>{
        this.$confirm(`预计发送短信人数为 ${response.data} 人，是否确认发送`, '提示', {
          confirmButtonText: '发送',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          smsSend(this.sms.bean.id,this.sms.classId,this.sms.trainFlag).then(response=>{
            this.sms = {open: false, bean: null, sended: false, content: '',classId:[],trainFlag:null}
            this.$modal.msgSuccess("发送成功")
            this.loading = false;
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消成功'
          });
        });
      })
    }
  }
};
</script>
